﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using System.IO;
using OfficeOpenXml.FormulaParsing.Excel.Functions.DateTime;
using System.Xml.Linq;
using System.Reflection.Metadata;
using OfficeOpenXml.FormulaParsing.Excel.Functions.RefAndLookup;
using Castle.Core.Resource;
using MailKit.Search;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 创建WMS物流发运单明细
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMStoWMSAddSalesInfoController : ControllerBase
    {
        private readonly ILogger _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_zh;
        public readonly string con_qh;
        public readonly string con_yb;


        public TMStoWMSAddSalesInfoController(ILogger<TMStoWMSAddSalesInfoRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {
            _WMSTokenCheckService = wmsTokenCheckService;
            con = _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_yb = _configuration.GetConnectionString("WMSDbConnection_YB");
            _logger = loggerFactory.CreateLogger<TMStoWMSAddSalesInfoController>();
        }

        /// <summary>
        /// 创建WMS物流发运单明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWMSAddSalesInfo([FromBody] TMStoWMSAddSalesInfoRequestDto strparm)
        {
            string strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            TMStoWMSAddSalesInfoResponseDto re = new TMStoWMSAddSalesInfoResponseDto();
            string waybill_no = strparm.waybill_no;
            string in_con = "";//目标WMS数据库
            try
            {
                if (waybill_no == "")
                {
                    strMsg = "waybill_no must be not null";
                }
                if (strparm.factory_code == "")
                {
                    strMsg = "factory_code must be not null";
                }
                else
                {
                    if (strparm.factory_code.Contains("zh"))
                    {
                        in_con = con_zh;
                    }
                    else
                    {
                        if (strparm.factory_code.Contains("qh"))
                        {
                            in_con = con_qh;
                        }
                        else
                        {
                            if (strparm.factory_code.Contains("sc"))
                            {
                                in_con = con_yb;
                            }
                            else
                            {
                                if (strparm.factory_code.Contains("gz"))
                                {

                                }
                                else
                                {
                                    strMsg = "factory_code=<" + strparm.factory_code + "> not find ";
                                }                                
                            }
                        }
                    }
                }

                if (strMsg == "")
                {
                    if (strparm.factory_code.Contains("gz"))
                    {

                        dic = new Dictionary<string, string>(); //查询公用dic
                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                        DataTable so_dt = MethodHelp.GetTableInfo("TMS0069", dic, con);//获取物流计划明细，订单数据源
                        if (so_dt.Rows.Count>0)
                        {
                            DataTable dt_type= MethodHelp.GetTableInfo("TMS0142", dic, con);//获取物流发运单，配送类型，委外推CRM，非委外推WMS
                            if (dt_type.Rows.Count > 0)
                            {
                                //代工直接插入CRM外协挑库单
                                if (dt_type.Rows[0]["business_type"].ToString() == "代工配送")
                                {
                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("shipment_no", waybill_no);//查询对应物流计划
                                    DataTable dt_check = MethodHelp.GetTableInfo("TMS0144", dic, con);//查询当前外协挑库单是否存在
                                    if (dt_check.Rows.Count <= 0)
                                    {
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("shipment_no", waybill_no);//查询对应物流计划
                                        //DataTable dt_wx = MethodHelp.GetTableInfo("TMS0143", dic, con);//获取外协挑库单插入数据源
                                        DataTable dt_wx = MethodHelp.GetTableInfo("TMS0151", dic, con);//获取外协挑库单插入数据源
                                        if (dt_wx.Rows.Count > 0)
                                        {
                                            strSqlList = new List<string>();
                                            string times = DateTimeOffset.Now.ToUnixTimeSeconds().ToString();
                                            dic = new Dictionary<string, string>();
                                            dic.Add("document_id", times);
                                            dic.Add("shipment_no", waybill_no);
                                            dic.Add("shipment_date", dt_wx.Rows[0]["shipping_date"].ToString());
                                            string sqlstr = MethodHelp.GetTranSQL("TMS0145", dic, con);//外协挑库单，主表插入语句
                                            if (sqlstr != "")
                                            {
                                                strSqlList.Add(sqlstr);

                                                foreach (DataRow item in dt_wx.Rows)
                                                {
                                                    dic = new Dictionary<string, string>();
                                                    dic.Add("document_id", times);
                                                    dic.Add("shipment_no", waybill_no);
                                                    dic.Add("customer_name", item["customer_name"].ToString());
                                                    dic.Add("customer_code", item["customer_code"].ToString());
                                                    dic.Add("saleorder_no", item["saleorder_no"].ToString());
                                                    dic.Add("saleorderline_no", item["saleorderline_no"].ToString());
                                                    dic.Add("material_code", item["material_code"].ToString());
                                                    dic.Add("material_name", item["material_name"].ToString());
                                                    dic.Add("saleorder_qty", item["saleorder_qty"].ToString());
                                                    dic.Add("ship_qty", item["ship_qty"].ToString());
                                                    dic.Add("customer_contacts", item["customer_contacts"].ToString());
                                                    dic.Add("contacts_tel", item["contacts_tel"].ToString());
                                                    dic.Add("shipping_address", item["shipping_address"].ToString());
                                                    dic.Add("delivery_address", item["delivery_address"].ToString());
                                                    dic.Add("plan_no_id", item["plan_no"].ToString());
                                                    dic.Add("plan_no", item["deliverno"].ToString());
                                                    string sqlstr2 = MethodHelp.GetTranSQL("TMS0150", dic, con);//外协挑库单，明细表插入语句
                                                    if (sqlstr2 != "")
                                                    {
                                                        strSqlList.Add(sqlstr2);
                                                    }
                                                }

                                            }

                                            if (strMsg == "")
                                            {
                                                if (strSqlList.Count > 0)
                                                {
                                                    bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                    if (A)
                                                    {

                                                    }
                                                    else
                                                    {
                                                        strMsg = "Database update failed";
                                                    }

                                                }
                                                else
                                                {
                                                    strMsg = "No insertion data present";
                                                }
                                            }

                                        }
                                        else
                                        {
                                            strMsg = "运单=<" + waybill_no + "> 获取订单明细失败，请联系管理员!";
                                        }
                                    }
                                    else
                                    {
                                        strMsg = "运单=<" + waybill_no + "> 已存在CRM，外协挑库单，插入失败请联系相关人员删除后，再试!";
                                    }

                                }
                                //推送组件富勒WMS
                                else
                                {
                                    WMS_SalesOrderCreateRequestDto data = new WMS_SalesOrderCreateRequestDto();
                                    WMS_SalesOrderCreateHeaderDto header = new WMS_SalesOrderCreateHeaderDto();
                                    List<WMS_SalesOrderCreateHeader> header_input = new List<WMS_SalesOrderCreateHeader>();
                                    foreach (DataRow item in so_dt.Rows)
                                    {
                                        dic = new Dictionary<string, string>(); //查询公用dic
                                        dic.Add("waybill_no", waybill_no);//查询对应物流计划
                                        dic.Add("saleorder_no", item["saleorder_no"].ToString());//查询对应物流计划
                                        DataTable sod_dt = MethodHelp.GetTableInfo("TMS0070", dic, con);//获取物流计划明细，订单数据源
                                        if (sod_dt.Rows.Count > 0)
                                        {
                                            List<WMS_SalesOrderCreate_Details> details_input = new List<WMS_SalesOrderCreate_Details>();
                                            //循环插入明细
                                            foreach (DataRow row in sod_dt.Rows)
                                            {
                                                details_input.Add(new WMS_SalesOrderCreate_Details
                                                {
                                                    orderLineNo = DB.ToInt(row["saleorderline_no"].ToString()),
                                                    sku = row["material_code"].ToString(),
                                                    qtyOrdered = DB.ToInt(row["ship_qty"].ToString()),
                                                    dedi03 = row["saleorderline_no"].ToString(),
                                                    dedi05 = row["saleorderline_no"].ToString(),
                                                    dedi06 = row["plan_no"].ToString()
                                                });
                                            }

                                            //添加到header
                                            if (details_input != null)
                                            {
                                                header_input.Add(new WMS_SalesOrderCreateHeader
                                                {
                                                    warehouseId = "H01",
                                                    customerId = "H01",
                                                    orderType = "GLJY",
                                                    soReference1 = item["saleorder_no"].ToString(),
                                                    soReference2 = item["saleorder_no"].ToString(),
                                                    soReference3 = item["waybill_no"].ToString(),
                                                    consigneeId = item["customer_code"].ToString(),
                                                    consigneeName = item["customer_name"].ToString(),
                                                    hedi04 = "H01",
                                                    hedi05 = "APPROVE",
                                                    details = details_input
                                                });
                                            }


                                        }
                                        else
                                        {
                                            strMsg = "logistics_plan_no=<" + waybill_no + "> ,订单号=<" + item["salesorderno"].ToString() + ">找不到对应明细信息!";
                                        }

                                    }

                                    if (header_input != null)
                                    {
                                        header.header = header_input;
                                    }
                                    if (header != null)
                                    {
                                        data.data = header;
                                    }


                                    if (data != null)
                                    {
                                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                                        urldic.Add("function_description", "内部:组件WMS_销售订单新增");//查看URL配置表地址描述
                                        DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                                        if (url_dt.Rows.Count > 0)
                                        {
                                            string jsonText = JsonConvert.SerializeObject(data);
                                            var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                            WMS_SalesOrderCreateResponseDto psp = JsonConvert.DeserializeObject<WMS_SalesOrderCreateResponseDto>(reAgv);
                                            if (psp.code > 0)
                                            {
                                                strMsg = "组件WMS返回错误:" + psp.message;
                                            }
                                        }
                                    }

                                }
                            }
                            else
                            {
                                strMsg = "运单=<" + waybill_no + ">，TMS0142，获取不到业务类型 !";

                            }
                        }
                        else
                        {
                            strMsg = "logistics_plan_no=<" + waybill_no + "> 找不到对应订单信息!";
                        }
                    }                                                       
                }
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

            if (strMsg == "")
            {
                re.code = 0;
                re.message = "";
            }
            else
            {
                re.code = 500;
                re.message = strMsg;

            }


            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);

        }


    }
}
